package demo.node;


import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author : feixiang.li
 * @since : 2025-09-19 13:35
 */
public class Solution_23 {


    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        // 优先级队列
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        for (ListNode list : lists) {
            if (list != null) {
                ListNode node = list;
                while (node != null) {
                    queue.offer(node);
                    node = node.next;
                }
            }
        }
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while (!queue.isEmpty()) {
            ListNode node = queue.poll();
            cur.next = node;
            cur = node;
        }
        cur.next = null;
        return dummy.next;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(4);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(2);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(2);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        ListNode node7 = new ListNode(1);
        ListNode node8 = new ListNode(3);
        ListNode node9 = new ListNode(4);
        node7.next = node8;
        node8.next = node9;
        ListNode node10 = new ListNode(2);
        ListNode node11 = new ListNode(6);
        node9.next = node10;
        node10.next = node11;
        ListNode[] lists = new ListNode[]{node1, node7, node10};
        ListNode mergeKLists = new Solution_23().mergeKLists(lists);
        while (mergeKLists != null) {
            System.out.println(mergeKLists.val);
            mergeKLists = mergeKLists.next;
        }
    }
}
